<!--<script src="http://server.chat:8080/socket.io/socket.io.js"></script>-->
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script>
	//var socket = io.connect('http://server.chat:8080');
	var name = 'GUEST';
	$(function() {
		$('#submit').click(function() {
			var message = $('#message').val();
			$('#message').val('');
			$('#content').append('<br/>' + name + ': ' + message);
			var param = {
				'type': 'send_message',
				'id': 'all',
				'sender': name,
				'message': message,
			};
			sendMessage(param);
		});
		
		connection();
		
		//setInterval(getMessage, 1000);
		getMessage();
	});
	
	function connection() {
		var code = /[A-z0-9\-\_]+/;
		while (name == 'GUEST' || !name.match(code)) {
			name = prompt('What\'s your name');
		}
		var time = new Date().getTime();
		var data = {
			'name': name,
			't': time,
		};
		$.ajax({
			url: 'http://server.chat:8080/connect',
			type: 'GET',
			data: $.param(data),
		}).done(function(response) {
			var res = JSON.parse(response);
			if (res.error) {
				alert(res.error);
				name = 'GUEST';
				connection();
				return;
			}
			$('#content').append('<br/>' + name + ': CONNECTED');
		});
	}
	
	function sendMessage(data) {
		var time = new Date().getTime();
		data['t'] = time;
		$.ajax({
			url: 'http://server.chat:8080/chat',
			type: 'POST',
			data: $.param(data),
		});
	}
	
	function getMessage() {
		var time = new Date().getTime();
		var data = {
			'type': 'listen',
			'id': 'all',
			't': time,
		};
		$.ajax({
			url: 'http://server.chat:8080/chat',
			type: 'POST',
			//dataType: 'json',
			data: $.param(data),
		}).done(function(response) {
			var v = JSON.parse(response);
			if (typeof v == 'object' && typeof v.sender == 'string') {
				if (v.sender !== name) {
					$('#content').append('<br/>' + v.sender + ': ' + v.message);
				}
			}
			getMessage();
		});
	}
	
	
</script>

<input type="text" id="message"/>
<input type="button" id="submit" value="push"/>
<br/>
<div id="content"></div>